// // 云函数入口文件
// const cloud = require('wx-server-sdk')

// cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

// // 云函数入口函数
// exports.main = async (event, context) => {
//   const wxContext = cloud.getWXContext()

//   return {
//     event,
//     openid: wxContext.OPENID,
//     appid: wxContext.APPID,
//     unionid: wxContext.UNIONID,
//   }
// }
const cloud = require('wx-server-sdk');
cloud.init();

exports.main = async (event, context) => {
  const { recordId } = event;
  const db = cloud.database();

  if (!recordId) {
    return { success: false, message: '缺少必要参数 recordId' };
  }

  try {
    // 查询记录
    const recordRes = await db.collection('records').doc(recordId).get();
    const record = recordRes.data;

    if (!record) {
      return { success: false, message: '记录不存在' };
    }

    if (record.status !== 'pending') {
      return { success: false, message: '该记录已处理' };
    }

    // 遍历物料并更新库存
    for (const item of record.items || []) {
      const stockRes = await db.collection('items')
        .where({ materialNumber: item.materialNumber })
        .get();

      if (!stockRes.data || stockRes.data.length === 0) {
        return { success: false, message: `物料编码 ${item.materialNumber} 不存在` };
      }

      const stock = stockRes.data[0];
      if (stock.quantity < item.quantity) {
        return { success: false, message: `库存不足：${item.materialName}` };
      }

      // 更新库存
      await db.collection('items').doc(stock._id).update({
        data: { quantity: stock.quantity - item.quantity },
      });
    }

    // 更新记录状态为 "approved"
    await db.collection('records').doc(recordId).update({
      data: {
        status: 'approved',
        approver: '管理员',
        approvalDate: new Date(),
      },
    });

    return { success: true, message: '批准成功' };
  } catch (err) {
    console.error(err);
    return { success: false, message: '操作失败，请稍后重试!' };
  }
};